package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.web.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/jsonServlet")
public class Demo04JsonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User(1, "jack", "666");

        // 1.将Java对象转为JSON字符串
        String jsonStr = JSON.toJSONString(user);
        System.out.println(jsonStr);

        // 2.将JSON字符串转为Java对象
        // {"id":1,"password":"666","username":"jack"}
        String jsonStr2 = "{\"id\":1,\"password\":\"666\",\"username\":\"jack\"}";
        User user1 = JSON.parseObject(jsonStr2, User.class);
        System.out.println("user1 = " + user1);
    }
}
